package bhwz.seac3.bl.import_;

import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import bhwz.seac3.blservice.ReDisplayControllerBLService;
import bhwz.seac3.blservice.import_.ErrorLogPrinter;
import bhwz.seac3.blservice.import_.ImportBLService;

public class ImportBL implements ImportBLService {
	ReDisplayControllerBLService autoDisplayController;
	
	public ImportBL(ReDisplayControllerBLService autoDisplayController){
		this.autoDisplayController=autoDisplayController;
	}

	@Override
	public void _import(String path, ErrorLogPrinter elp) {
		File file = new File(path);
		if (file.isDirectory()) {
			if (isDirectoryCorrect(file)) {
				File[] files = file.listFiles();
				Map<String, File> fileMap = new HashMap<>();
				for (File f : files) {
					fileMap.put(f.getName(), f);
				}
				PlayerImportBL pBl = new PlayerImportBL();
				File[] playerSons = fileMap.get("players").listFiles();
				for (File p : playerSons) {
					switch (p.getName()) {
					case "info":
						pBl.importPlayerInfo(p.getPath(), elp);
						break;
					case "portrait":
						new Thread() {
							@Override
							public void run() {
								pBl.importPlayerPortraitPicture(p.getPath(),
										elp);
							}
						}.start();
						break;
					case "action":
						new Thread() {
							@Override
							public void run() {
								pBl.importPlayerActionPicture(p.getPath(), elp);
							}
						}.start();

						break;
					}
				}
				TeamImportBL tBl = new TeamImportBL();
				tBl.importTeam(fileMap.get("teams").getPath(), elp);
				File matchesFile = fileMap.get("matches");
				if (matchesFile.list().length != 0) {
					MatchImportBL mBl = new MatchImportBL(autoDisplayController);
					mBl.importMatch(fileMap.get("matches").getPath(), elp);
				}
				/* 监听文件夹 */
				try {
					WatchDir watcher = new WatchDir(autoDisplayController,fileMap.get("matches")
							.toPath(), false);
					Thread watchDir=new Thread(){
						@Override
						public void run() {
							watcher.processEvents(elp);
						}
					};
					watchDir.start();
				} catch (IOException e) {
					e.printStackTrace();
				}

			} else {
				elp.print("文件夹格式不正确!");
			}
		} else {
			elp.print("path is not a directory!");
		}
		elp.print("导入完成!");
	}

	private boolean isDirectoryCorrect(File file) {
		List<String> s = Arrays.asList(file.list());
		if (s.contains("matches") && s.contains("players")
				&& s.contains("teams") == true) {
			File[] files = file.listFiles();
			for (File f : files) {
				if (f.getName().equals("players")) {
					List<String> fs = Arrays.asList(f.list());
					return fs.contains("action") && fs.contains("info")
							&& fs.contains("portrait");
				}
			}
		}
		return false;

	}

	

}
